package com.walker.util;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XmlUtil {

	@SuppressWarnings("unchecked")
	public static List<?> getListXml(InputStream is, Class<?> clazz) {
		Object obj = null;
		List<Object> result = new ArrayList<Object>();
		try {
			// 1.创建Reader对象
			SAXReader reader = new SAXReader();
			// 2.加载xml
			Document document = reader.read(is);
			// 3.获取根节点
			Element rootElement = document.getRootElement();
			Iterator<Element> iterator = rootElement.elementIterator();
			while (iterator.hasNext()) {
				obj = clazz.newInstance();
				Element stu = iterator.next();
				List<Attribute> attributes = stu.attributes();
				for (Attribute attribute : attributes) {
					String name = attribute.getName();
					name = name.substring(0, 1).toUpperCase() + name.substring(1);
					String value = attribute.getText();

					Method m = obj.getClass().getMethod("set" + name, String.class);
					m.invoke(obj, value);
				}
				result.add(obj);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}
}
